package com.zzyl.nursing.member.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.member.domain.FamilyMember;
import com.zzyl.nursing.member.dto.MiniProgramLoginDto;
import com.zzyl.nursing.member.service.MiniProgramLoginService;
import com.zzyl.nursing.member.vo.MiniProgramLoginVo;
import com.zzyl.nursing.member.mapper.MiniProgramLoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class MiniProgramLoginServiceImpl implements MiniProgramLoginService {
    @Value("${Wechat.appId}")
    private String appID;

    @Value("${Wechat.appSecret}")
    private String appSecret;

    @Autowired
    private MiniProgramLoginMapper miniProgramLoginMapper;

    @Autowired
    private TokenService tokenService;

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public MiniProgramLoginVo login(MiniProgramLoginDto dto) {
        //判断数据库内是否存在该用户
        LambdaQueryWrapper<FamilyMember> wrapper = new LambdaQueryWrapper<FamilyMember>()
                .eq(FamilyMember::getOpenId, dto.getCode());
        FamilyMember familyMember = miniProgramLoginMapper.selectOne(wrapper);
        MiniProgramLoginVo result = new MiniProgramLoginVo();
        if (ObjectUtil.isNotEmpty(familyMember)) {
            Long id = familyMember.getId();
            String phone = familyMember.getPhone();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", id);
            hashMap.put("phone", phone);
            String token = tokenService.createToken(hashMap);
            result.setToken(token);
            result.setNickName(familyMember.getName());
        } else {
            FamilyMember member = new FamilyMember();
            String code = dto.getPhoneCode();

            //获取access_token
            String urlToken = "https://api.weixin.qq.com/cgi-bin/token";
            HashMap<String, Object> mapToken = new HashMap<>();
            mapToken.put("grant_type", "client_credential");
            mapToken.put("appid", appID);
            mapToken.put("secret", appSecret);
            String resultInside = HttpUtil.get(urlToken, mapToken);
            String access_token = JSONUtil.parseObj(resultInside).getStr("access_token");

            //获取手机号
            String urlPhone = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
            Map<String, Object> mapPhone = new HashMap<>();
            urlPhone += "?access_token=" + access_token;
            //mapPhone.put("access_token", access_token);
            mapPhone.put("code", code);
            resultInside = HttpUtil.post(urlPhone, JSONUtil.toJsonStr(mapPhone));
            String phone = JSONUtil.parseObj(resultInside).getJSONObject("phone_info").getStr("phoneNumber");

            member.setPhone(phone);
            member.setName("微信用户");
            member.setOpenId(dto.getCode());
            member.setCreateTime(new DateTime().now());
            miniProgramLoginMapper.insert(member);

            //生成token
            Long id = member.getId();
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("id", id);
            hashMap.put("phone", phone);
            String token = tokenService.createToken(hashMap);
            result.setToken(token);
            result.setNickName(member.getName());
        }
        return result;
    }
}
